package com.sunday.player.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;

import com.sunday.player.domain.musicData;
import com.sunday.player.domain.musiclist;
import com.sunday.player.service.sundayplayerProvider;


/**
 * DB 관리자
 * @author user
 *
 */
public class listDBcontroler {
    private Context mcontext;
    private Uri listUri =sundayplayerProvider.listInfo.CONTENT_URI_LIST;
    private Uri musicUri =sundayplayerProvider.musicInfo.CONTENT_URI_MUSIC;
    private Uri PLaylistUri =sundayplayerProvider.playlist.CONTENT_URI_PLayList;
    
    
    public listDBcontroler(Context mcContext) {
	mcontext = mcContext;
    }
    /**
     * 리스트와 목록을 생성
     * @param item
     */
    public boolean list_make(musiclist item){
	String _id = null;
	ContentValues CV = new ContentValues();
	CV.put(sundayplayerProvider.MusicList[1], item.getListName());
	CV.put(sundayplayerProvider.MusicList[2], item.isCheck());
	
	
	if(item.getListid() != null){
	    Cursor c = mcontext.getContentResolver().query(listUri, new String[]{"listid"}, "listinfo.listname = '"+item.getListName()+"'", null, null);
	   if(c.getCount() > 0){
	       return false;
	   }
	   
	}else{
	    
	    Uri insert = mcontext.getContentResolver().insert(listUri, CV);
	    _id = Long.toString(ContentUris.parseId(insert));
	    item.setListid(_id);
	}
	
	
	 item_insertAll(item.getMusiclist() , item);
	
	 copyDB();
	 return true;
    }
    /**
     * 리스트와 목록삭제 
     * @param item
     */
    public boolean list_delete(musiclist item){
	mcontext.getContentResolver().delete(listUri, "_id = '"+item.getListid()+"'", null);
	mcontext.getContentResolver().delete(musicUri, "listid = '"+item.getListid()+"'", null);
	copyDB();
	return true;
    }
    public List<musiclist> list_Call_All(){
	List<musiclist> musicList = new ArrayList<musiclist>();
	try {
	    Cursor c = mcontext.getContentResolver().query(listUri, sundayplayerProvider.MusicList, null, null, null);
	    c.moveToFirst();
	    do{
		musiclist item = new musiclist(c);
		item.setMusiclist(Item_get(item.getListid()));
		musicList.add(item);
	    }while(c.moveToNext());
	    
	} catch (Exception e) {
	    e.printStackTrace();
	}
	return musicList;
	
	
    }
    /**
     * 리스트 수정
     * @param item
     */
    public void list_edit(musiclist item , int type){
	
    }
    /**
     * 리스트 전체 삽입
     * @param itemlist 
     */
    public void item_insertAll(List<musicData> musicList, musiclist itemlist){
	
	try {
	    for(musicData item : musicList){
		ContentValues cv = new ContentValues(10);
		item.setListid(itemlist.getListid());
		cv.put(sundayplayerProvider.MusicInfo[1], item.getListid());
		cv.put(sundayplayerProvider.MusicInfo[2], item.getTitle());
		cv.put(sundayplayerProvider.MusicInfo[3], item.getTrack());
		cv.put(sundayplayerProvider.MusicInfo[4], item.getDuration());
		cv.put(sundayplayerProvider.MusicInfo[5], item.getAlbum_id());
		cv.put(sundayplayerProvider.MusicInfo[6], item.getAlbum());
		cv.put(sundayplayerProvider.MusicInfo[7], item.getArtist_id());
		cv.put(sundayplayerProvider.MusicInfo[8], item.getArtist());
		cv.put(sundayplayerProvider.MusicInfo[9], item.get_data());
		cv.put(sundayplayerProvider.MusicInfo[10], item.getCount());
		Uri insert = mcontext.getContentResolver().insert(musicUri	,	cv);
		String  _id = Long.toString(ContentUris.parseId(insert));
		item.set_id(_id);
		playerControl.Trace_i(item.getTitle()+" = "+_id, playerControl.TAG);
	    }
	} catch (Exception e) {
	    e.printStackTrace();
	}
	
	
    }
    
    /**
     * 플레이 리스트 전체 삽입
     * @param itemlist 
     */
    public void playList_insertAll(List<musicData> musicList){
	copyDB();
	try {
	    for(musicData item : musicList){
		ContentValues cv = new ContentValues(10);
		item.setListid("PLAYLIST");
		cv.put(sundayplayerProvider.MusicInfo[1], item.getListid());
		cv.put(sundayplayerProvider.MusicInfo[2], item.getTitle());
		cv.put(sundayplayerProvider.MusicInfo[3], item.getTrack());
		cv.put(sundayplayerProvider.MusicInfo[4], item.getDuration());
		cv.put(sundayplayerProvider.MusicInfo[5], item.getAlbum_id());
		cv.put(sundayplayerProvider.MusicInfo[6], item.getAlbum());
		cv.put(sundayplayerProvider.MusicInfo[7], item.getArtist_id());
		cv.put(sundayplayerProvider.MusicInfo[8], item.getArtist());
		cv.put(sundayplayerProvider.MusicInfo[9], item.get_data());
		cv.put(sundayplayerProvider.MusicInfo[10], item.getCount());
		Uri insert = mcontext.getContentResolver().insert(PLaylistUri	,	cv);
		String  _id = Long.toString(ContentUris.parseId(insert));
		item.set_id(_id);
		playerControl.Trace_i(item.getTitle()+" = "+_id, playerControl.TAG);
	    }
	} catch (Exception e) {
	    e.printStackTrace();
	}
	
	
    }
    public List<musicData> playList_get( ){
   	List<musicData> musicList = new ArrayList<musicData>();
   	try {
   	    Cursor c = mcontext.getContentResolver().query(PLaylistUri, sundayplayerProvider.MusicInfo, null, null, null);
   	    c.moveToFirst();
   	    if(c.getCount() == 0){
   		return musicList;
   	    }
   	    do{
   		for(int a= 0 ; a < c.getColumnCount() ; a++){
   			playerControl.Trace_i(a+" DBmp3 = "+c.getColumnName(a)+" = "+c.getString(a), playerControl.TAG);
   		}
   		musicData item = new musicData(c , "PLAYLIST");
   		musicList.add(item);
   	    }while(c.moveToNext());
   	    
   	} catch (Exception e) {
   	    e.printStackTrace();
   	}
   	return musicList;
   	
       }
    public List<musicData> Item_get(String ListId){
	List<musicData> musicList = new ArrayList<musicData>();
	try {
	    Cursor c = mcontext.getContentResolver().query(musicUri, sundayplayerProvider.MusicInfo, "listid = '"+ListId+"'", null, null);
	    c.moveToFirst();
	    playerControl.Trace_i(ListId + "Item_get = "+c.getCount(), playerControl.TAG);
	    if(c.getCount() == 0){
		return musicList;
	    }
	    do{
		for(int a= 0 ; a < c.getColumnCount() ; a++){
			playerControl.Trace_i(a+" DBmp3 = "+c.getColumnName(a)+" = "+c.getString(a), playerControl.TAG);
		}
		musicData item = new musicData(c , ListId);
		musicList.add(item);
	    }while(c.moveToNext());
	    
	} catch (Exception e) {
	    e.printStackTrace();
	}
	return musicList;
	
    }
    
    /**
	 * 내부 DB 확인을 위해 SD 카드로 DB 파일을 복사
	 * @param mContext
	 */
	public void copyDB(){
		
		AssetManager manager = mcontext.getAssets();
		String folderPath = "/data/data/com.sunday.player/databases";
		String filePath = "/data/data/com.sunday.player/databases/"+sundayplayerProvider.INTERNAL_DB_NAME;
		String outfIle  = Environment.getExternalStorageDirectory().toString()+"/"+sundayplayerProvider.INTERNAL_DB_NAME;
		File folder = new File(folderPath);
		File file = new File(filePath);
		File outFuile = new File(outfIle);
		if(outFuile.isFile()){
		    outFuile.delete();
		}
		FileOutputStream fos = null;
		BufferedOutputStream bos = null;
		try {
			FileInputStream in = new FileInputStream(file);
			//       InputStream is = manager.open("db/monkey3.db");
			BufferedInputStream bis = new BufferedInputStream(in);

			if (folder.exists()) {

			}else{
				folder.mkdirs();
			}


			if (outFuile.exists()) {
				outFuile.delete();
				outFuile.createNewFile();
			}

			fos = new FileOutputStream(outFuile);
			bos = new BufferedOutputStream(fos);
			int read = -1;
			byte[] buffer = new byte[1024];
			while ((read = bis.read(buffer, 0, 1024)) != -1) {
				bos.write(buffer, 0, read);
			}

			bos.flush();

			bos.close();
			fos.close();
			bis.close();
			in.close();

		} catch (IOException e) {
			e.printStackTrace();
			Log.e("ErrorMessage : ", e.getMessage());
		}
	}
    
    
}
